<template>

  <el-button type="success" @click="dialogTableVisible = true">
    新增用户
  </el-button>

  <el-table :data="tableData" border style="width: 100%">
    <el-table-column fixed type="index" label="编号"  />
    <el-table-column prop="userName" label="用户名"/>
    <el-table-column prop="sex" label="性别">
        <template v-slot="a">
            <el-tag type="success" v-if="a.row.sex==true">男</el-tag>
            <el-tag type="warning" v-else>女</el-tag>
        </template>
    </el-table-column>
    <el-table-column prop="roleName" label="角色名称"/>
    <el-table-column prop="provinceName" label="所在省份">
      <template v-slot="a">
         {{ getProvinceName(a.row.provinceName) }}
      </template>
    </el-table-column>
    <el-table-column prop="cityName" label="所在市">
      <template v-slot="a">
         {{ getCityName(a.row.cityName) }}
      </template>
    </el-table-column>
    <el-table-column prop="regionName" label="所在县" >
      <template v-slot="a">
         {{ getRegionName(a.row.regionName) }}
      </template>
    </el-table-column>
    <el-table-column  prop="detail_Address" label="地址详情" width="110px">
        <template v-slot="a">
            <div class="row center">
            <el-tooltip
                class="box-item"
                effect="dark"
                :content=a.row.detail_Address
                placement="top-start"
            >
            <span v-if="a.row.detail_Address.length>5">{{ a.row.detail_Address.substring(0,5)+'...' }}</span>
            <span v-else>{{ a.row.detail_Address }}</span>
            </el-tooltip>
            </div>
        </template>
    </el-table-column>
    
    
    <el-table-column prop="createName" label="创建人"/>
    <el-table-column prop="createDate" label="创建日期" width="180px">
        <template v-slot="a">
            <span>{{ a.row.createDate==null?"":moment(a.row.createDate).format("YYYY-MM-DD  HH:mm:ss") }}</span>
        </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人"/>
    <el-table-column prop="updateDate" label="修改日期" width="180px">
        <template v-slot="a">
            <span>{{ a.row.updateDate==null?"": moment(a.row.updateDate).format("YYYY-MM-DD  HH:mm:ss") }}</span>
        </template>
    </el-table-column>
    <el-table-column prop=" " label="操作" width="300px">
        <template v-slot="a">
            <el-button type="primary" @click="edit(a.row)">修改</el-button>
            <el-button type="danger" @click="del(a.row.id,a.row.userName)">删除</el-button>
            <el-button type="warning" v-if="a.row.isManager==false" @click="updatefuze(a.row.id,true,'设为部门负责人')">设为部门负责人</el-button>
            <el-button type="info" v-else @click="updatefuze(a.row.id,false,'取消部门负责人')">取消部门负责人</el-button>
        </template>
    </el-table-column>
  </el-table>

  <!-- 新增用户 -->
   <el-dialog v-model="dialogTableVisible" title="新增用户" width="800">
      
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
        >
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="ruleForm.userName" />
            </el-form-item>

            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="ruleForm.sex">
                    <el-radio :value="true">男</el-radio>
                    <el-radio :value="false">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- <el-form-item label="所在地址">
              
                <el-select v-model="ruleForm.provinceId" placeholder="请选择省份" style="width:150px;margin-right: 22px;" @change="getcitybuproid">
                    <el-option v-for="item in provinceList" :label="item.provinceName" :value="item.id" />
                </el-select>

                <el-select v-model="ruleForm.cityId" placeholder="请选择市" style="width:150px;margin-right: 22px;" @change="getcountrybucityid">
                    <el-option v-for="item in cityList" :label="item.cityName" :value="item.id" />
                </el-select>

                <el-select v-model="ruleForm.countryId" placeholder="请选择县" style="width:150px">
                    <el-option v-for="item in countryList" :label="item.countryName" :value="item.id" />
                </el-select>
            </el-form-item> -->

            


            <el-form-item label="区域选择">
              <el-select 
                v-model="ruleForm.provinceName" 
                placeholder="请选择省份" 
                @change="handleProvinceChange"
                style="width: 120px; margin-right: 8px;"
              >
                <el-option 
                  v-for="item in provinceList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>

              <!-- 城市选择（依赖省份） -->
              <el-select 
                v-model="ruleForm.cityName" 
                placeholder="请选择市" 
                @change="handleCityChange"
                style="width: 120px; margin-right: 8px;"
              >
                <el-option 
                  v-for="item in cityList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>

              <!-- 区县选择（依赖城市） -->
              <el-select 
                v-model="ruleForm.regionName" 
                placeholder="请选择县" 
                style="width: 120px;"
              >
                <el-option 
                  v-for="item in districtList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="详细地址" prop="detail_Address">
              <el-input v-model="ruleForm.detail_Address" />
            </el-form-item>

            <el-form-item label="部门:" prop="departmentId">
              <el-select v-model="ruleForm.departmentId" placeholder="请选择">
                <el-option label="IT信息部" :value="1" />
                <el-option label="人力资源部" :value="2" />
                <el-option label="财务部" :value="3" />
                <el-option label="销售部" :value="4" />
                <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>


            
            
            
            <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
   </el-dialog>


   <!-- 修改用户 -->
   <el-dialog v-model="dialogTableVisibleUpdate" title="编辑用户" width="800">
      
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
        >
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="ruleForm.userName" />
            </el-form-item>

            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="ruleForm.sex">
                    <el-radio :value="true">男</el-radio>
                    <el-radio :value="false">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- <el-form-item label="所在地址">
                <el-select v-model="ruleForm.provinceId" placeholder="请选择省份" style="width:150px;margin-right: 22px;" @change="getcitybuproid">
                    <el-option v-for="item in provinceList" :label="item.provinceName" :value="item.id" />
                </el-select>

                <el-select v-model="ruleForm.cityId" placeholder="请选择市" style="width:150px;margin-right: 22px;" @change="getcountrybucityid">
                    <el-option v-for="item in cityList" :label="item.cityName" :value="item.id" />
                </el-select>

                <el-select v-model="ruleForm.countryId" placeholder="请选择县" style="width:150px">
                    <el-option v-for="item in countryList" :label="item.countryName" :value="item.id" />
                </el-select>
            </el-form-item> -->


            <el-form-item label="区域选择">
              <el-select 
                v-model="ruleForm.provinceName" 
                placeholder="请选择省份" 
                @change="handleProvinceChange"
                style="width: 120px; margin-right: 8px;"
              >
                <el-option 
                  v-for="item in provinceList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>

              <!-- 城市选择（依赖省份） -->
              <el-select 
                v-model="ruleForm.cityName" 
                placeholder="请选择市" 
                @change="handleCityChange"
                style="width: 120px; margin-right: 8px;"
              >
                <el-option 
                  v-for="item in cityList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>

              <!-- 区县选择（依赖城市） -->
              <el-select 
                v-model="ruleForm.regionName" 
                placeholder="请选择县" 
                style="width: 120px;"
              >
                <el-option 
                  v-for="item in districtList" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value"
                />
              </el-select>
            </el-form-item>


            <el-form-item label="详细地址" prop="detail_Address">
              <el-input v-model="ruleForm.detail_Address" />
            </el-form-item>

            <el-form-item label="部门:" prop="departmentId">
              <el-select v-model="ruleForm.departmentId" placeholder="请选择">
                <el-option label="IT信息部" :value="1" />
                <el-option label="人力资源部" :value="2" />
                <el-option label="财务部" :value="3" />
                <el-option label="销售部" :value="4" />
                <el-option label="行政部" :value="5" />
                </el-select>
            </el-form-item>
            
            
            <el-form-item>
            <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">
                修改
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
   </el-dialog>


</template>

<script lang="ts" setup>
import { ref,reactive,onMounted, watch, nextTick } from 'vue';
import axios from 'axios';
import moment from 'moment';
import httpr from '@/axioslan/axioshttp'
import httpw from '@/axioslan/axioshttps'
onMounted(()=>
{
    search();
})

const tableData =ref([])
const search=()=>
{
    httpr
    ({
        url:'/api/User/GetUser',
        method:'get'
    })
    .then(res=>{
        tableData.value=res.data.data;
    })
}

//三级联动
// //获取省份
// const newprovinceList:any =ref([])
// const  getProvince=()=>
// {
//     axios
//     ({
//         url:'http://localhost:5145/api/City/GetProvince',
//         method:'get'
//     })
//     .then(res=>{
//         newprovinceList.value=res.data.data;
//     })
// }

// const getcitybuproid=(id:any)=>
// {
//     if(id)
//     {
//         getCity(id);
//     }
//     ruleForm.cityId='';
//     ruleForm.countryId='';
// }


// //获取市
// const newcityList:any =ref([])
// const getCity=(id:any)=>
// {
//     axios
//     ({
//         url:'http://localhost:5145/api/City/GetCity',
//         method:'get',
//         params:
//         {
//             provinceId:id
//         }
//     })
//     .then(res=>{
//         newcityList.value=res.data.data;
//     })
// }

// const getcountrybucityid=(id:any)=>
// {
//     if(id)
//     {
//         getCountry(id);
//     }
//     ruleForm.countryId='';
// }

// //获取县
// const newcountryList:any =ref([])
// const getCountry=(id:any)=>
// {
//     axios
//     ({
//         url:'http://localhost:5145/api/City/GetCountry',
//         method:'get',
//         params:
//         {
//             cityId:id
//         }
//     })
//     .then(res=>{
//         newcountryList.value=res.data.data;
//     })
// }


//新增用户
const dialogTableVisible = ref(false)
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
const router=useRouter();

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    id:'',
  userName: '',
  sex: true,
  // countryId: '',
  detail_Address: '',
  // provinceId:'',
  // cityId:'',
  departmentId:'',
  //全国选择
  cityName:"",
  regionName:"",
  provinceName:""
})


const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
  ],
  detail_Address: [
    {
      required: true,
      message: '详细地址不能为空',
      trigger: 'change',
    },
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      httpw
      ({
        url:'/api/User/CreateUser',
        method:'post',
        data:ruleForm
      })
      .then(res=>{
        if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            search();
            dialogTableVisible.value=false;
            ruleForm.userName='',
            ruleForm.sex=true,
            ruleForm.detail_Address=''
            // ruleForm.provinceId='',
            // ruleForm.cityId='',
            // ruleForm.countryId=''
            return;
        }
        else
        {
            ElMessage.error(res.data.msg);
            search();
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//编辑用户
const dialogTableVisibleUpdate = ref(false)
const edit=async (row:any)=>
{
    console.log(row);
    Object.assign(ruleForm,row);

    handleProvinceChange(row.provinceName);

    nextTick(()=>
  {
    ruleForm.cityName=row.cityName;

    handleCityChange(row.cityName);

    nextTick(()=>
    {
      ruleForm.regionName=row.regionName;
    })

  })
    
    // await getProvince();
    // await getCity(row.provinceId);
    // await getCountry(row.cityId);
    
   dialogTableVisibleUpdate.value=true;
}

const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      httpw
      ({
        url:'/api/User/UpdateUser',
        method:'put',
        data:ruleForm
      })
      .then(res=>{
        if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            search();
            dialogTableVisibleUpdate.value=false;
            dialogTableVisible.value=false;
            ruleForm.userName='',
            ruleForm.sex=true,
            ruleForm.detail_Address=''
            return;
        }
        else
        {
            ElMessage.error(res.data.msg);
            search();
        }
      })
    } else {
      console.log('error submit!', fields)
      router.push('/');
    }
  })
  
}

const del=(id:any,name:any)=>
{
  ElMessageBox.confirm(
    '您确认要删除用户['+name+']的信息吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      httpw
      ({
        url:'/api/User/DeleteUser',
        method:'delete',
        params:
        {
          id:id
        }
      })
      .then(res=>{
        if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            search();
            return;
        }
        else
        {
            ElMessage.error(res.data.msg);
            search();
            return;
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}





//区域选择
//省市县全国
import { regionData, codeToText } from 'element-china-area-data'

// 省份列表
const provinceList = regionData
// 城市列表
const cityList = ref<any[]>([])
// 区县列表
const districtList = ref<any[]>([])

// 使用你指定的ID名称


// 省份改变时，加载对应城市
const handleProvinceChange = (provinceCode: string) => {
  ruleForm.cityName=''
  ruleForm.regionName=''

  
  const province = regionData.find(item => item.value === provinceCode)
  if (province && province.children) {
    cityList.value = province.children
  } else {
    cityList.value = []
  }
}

// 城市改变时，加载对应区县
const handleCityChange = (cityCode: string) => {
    ruleForm.regionName=''
  
  const province = regionData.find(item => item.value === ruleForm.provinceName)
  if (province) {
    const city = province.children?.find(item => item.value === cityCode)

    if (city?.children) {
      districtList.value = city.children
    } else {
      districtList.value = []
      console.warn('当前城市无区县数据')
    }
  }
}
console.log(regionData); 
// 监听 provinceId 变化，初始化城市列表
watch(()=>ruleForm.provinceName, (newVal) => {
  if (newVal) {
    handleProvinceChange(newVal)
  }
})

// 监听 cityId 变化，初始化区县列表
watch(()=>ruleForm.cityName, (newVal) => {
  if (newVal) {
    handleCityChange(newVal)
  }
})
// 编码转名称的工具函数
const getProvinceName = (code: string) => codeToText[code] || '--'
const getCityName = (code: string) => codeToText[code] || '--'
const getRegionName = (code: string) => codeToText[code] || '--'




//将用户设为或取消部门负责人
const updatefuze=(id:any,fuze:any,name:any)=>
{
    ElMessageBox.confirm(
    '您确认要将用户['+name+']吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      httpw
      ({
        url:'/api/User/UpdateDepartmentFuZe',
        method:'put',
        data:
        {
          id:id,
          isManager:fuze
        }
      })
      .then(res=>{
        if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            search();
            return;
        }
        else
        {
            ElMessage.error(res.data.msg);
            search();
            return;
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}



</script>



<style>
.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>
<style scoped>
.text-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}
</style>
